A good answer might be:

Name: Amy Number: 123-4567

The equals( Object ) Method

class Entry
{
  String name;
  String number;

  . . . . .

  // methods
  public boolean equals( Object other )
  {
    return name.equals( ((Entry)other).name );
  }

  . . . . . 
}

Carefully study the equals( Object ) method. The reason for this phone book example is to discuss this method. This method presents a common problem (using an Object reference) and uses the typical solution (a type cast to a specific type.)

All classes have an equals( Object ) method because the Object class defines it. (You may wish to look at the Java documentation for Object at this point.) Most classes override the method with a more appropriate method.

The parameter list is ( Object other ). This says that equals() will be used with a reference to any other object. However, in our particular application we will be comparing two Entry objects with each other. (One entry will contain the name we are searching for; the other will be an entry in a Vector of data.)

We know what the parameter will be (since we are writing the code), but the compiler does not. Without more specific information, the compiler will assume only the methods and members of Object. To tell the compiler what to expect, a type cast must be used:

    return name.equals( ((Entry)other).name );

This tells the compiler that other is a reference to an Entry. This must be done to access the name field of the Entry object.


You might wonder: why not write the equals() method this way:

  public boolean equals( Entry other )
  {
    return name.equals( other.name );
  }
This is a correct method, but it does not override the equals( Object ) method that all objects have. It is this last method that is used with the indexOf() method. We must override it to use that built-in searching method of Vector.

QUESTION 21:

What will the compiler do with the following method:

class Entry
{
  . . . . .

  // methods
  public boolean equals( Object other )
  {
    return name.equals( other.name );
  }

  . . . . . 
}